var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var wxAuthFail = true;

var screen_w = 320;
var inviteuid= '';
var startX = 0;
Page({
  data: {
    util: util,
    host: util.api_host,
    tc: 0,
    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    version: util.version,
    token: '',
    uid: 0,
    coin: 0.00,
    userinfo: {},


    isShow: false,

    user_jifen: 0,

    has_cdb: false,


    waithao: false,
    ghsData:[],

    contact_phone: '',

    tuiwen1:'',
    tuiwen2:'',

    hiddenWidth:59,
    btnList: [{ right: -59 },
      { right: -59 },
      { right: -59 }],

    oldView: false,

    mendianId : '',
    tabcurrcata: 0,
  },
  onLoad: function (data) {

    var that=this;
    inviteuid = data.inviteuid ? data.inviteuid : '';
    console.log("util.orgid=="+util.orgid);
    if(util.orgid==18535){

      var roomstr = data.roomstr || '';
      var room = {};
      if (roomstr != '') {
        room = JSON.parse(roomstr);

        console.log("room====" + room);
        that.setData({
          oldView:true ,
          room: room,
          option:data
        })
      }
    }else if(util.orgid==17784 || util.orgid == 12809){
        console.log("==1==");
        that.setData({
          oldView:true ,

        })
      }

    console.log("inviteuid===="+inviteuid);
    this.setData({
      inviteuid:inviteuid,
    });
    this.getLoginInfo(inviteuid);
    var that = this;
    var tc = app.get_tc();//简体繁体转换
    that.setData({
      tc: tc
    })
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('mine/mine', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor
      });
    });
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
      that.resetNavColor();
    });


    wx.getSystemInfo({
      success: function (res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          windowWidth: wx.getSystemInfoSync().windowWidth,
          windowHeight: wx.getSystemInfoSync().windowHeight
        })
      }
    });
   

    //读取文字分类
    this.loadGHS(1);

    //联系信息
    app.getAllAbout('contact', function (res) {
      that.setData({
        contact_phone: res
      })
    });

    if (data.uidfromcircle) {
      that.setData({
        navFromCircle: true,
        uidFromCircle: data.uidfromcircle
      })
      console.log('that.data.navFromCircle', that.data.uidFromCircle)
      that.getCircleUserinfo(data.uidfromcircle)
    }

  },

   /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getLoginInfo(this.data.inviteuid);
  },
  gettuiwen: function (topicid,key){
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topicdetail",
      loginuid: that.data.uid ? that.data.uid : '',
      topicid: topicid,
    };
    console.log("动态详情请求参数：", params);
    //动态详情
    util.api({
      data: params,
      success: function (responseData) {
        var data = responseData.data;
        console.log("啊啊啊啊啊详情：", data);
        if(key == 2){
          that.setData({
            tuiwen2: data
          })
        }else{
          that.setData({
            tuiwen1: data
          })
        }
        
      }
    });
  },




  getLoginInfo: function (inviteuid) {
    var that = this;
    app.LoginUserInfo(function (res) {
      console.log("mine login:", res);
      wxAuthFail = res == -1;//用户拒绝授权
      if (wxAuthFail) {
        return;
      }
      that.setData({
        uid: res.uid,
        token: res.token
      });
      
      var id = inviteuid ? inviteuid : res.uid;
      util.api({
        data: {
          "uid": id,
          "publickey": util.publiccode,
          "ac": "userinfo"
        },
        success: function (responseData) {
          console.log("用户信息",responseData.data);
       
          var graphic1 = responseData.data.graphic1;
          var graphic2 = responseData.data.graphic2;
          console.log("graphic1", graphic1);
          console.log("graphic2", graphic2);
          if (graphic1 != '' && graphic1 != undefined) {
            that.gettuiwen(graphic1, 1);
          }

          if (graphic2 != '' && graphic2 != undefined) {
            that.gettuiwen(graphic2, 2);
          }

          that.setData({
            userinfo: responseData.data,
            mendianId: responseData.data.mendianid,
            markers: [{
              id: 1,
              latitude: responseData.data.lat,
              longitude: responseData.data.lon,
              name: responseData.data.address
            }],
          });
          
          var tc = app.get_tc();//简体繁体转换
          var titlename = tc == 1 ? '個人名片' : '个人名片';
          if (util.orgid == 15671){
            titlename = tc == 1 ? '個人簡歷' : '个人简历';
          }
          wx.setNavigationBarTitle({
            title: that.data.userinfo.uname+titlename,
          });  
          if(that.data.room){
            wx.setNavigationBarTitle({
              title: that.data.room.building + that.data.room.number + (tc == 1 ? '房間名片' : '房间名片'),
            });  
          }
        }
      });

      // var params = {
      //   "uid": res.uid,
      //   "publickey": util.publiccode,
      //   "ac": "coininfo",
      //   "privatekey": utilMd5.hexMD5(res.uid + 'coininfo' + res.token)
      // };
      // console.log("余额参数：uid=" + res.uid + "; token = " + res.token, params);
      // util.api({
      //   method: "post",
      //   data: params,
      //   success: function (responseData) {
      //     console.log("余额返回：", responseData);
      //     that.setData({
      //       coin: (responseData.data.coin || 0) / 100
      //     });
      //   }
      // });

      util.api({
        data: {
          "publickey": util.publiccode,
          "ac": "wxcheck"
        },
        success: function (responseData) {
          that.setData({
            isShow: !responseData.data.isShow
          });
        }
      });
    });

    that.setData({
      timeStamp:new Date().getTime()
    })
  },



  //重新读取 登录用户信息
  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },
  goAtherPage: function (e) {
    app.saveFormId(e.detail.formId);
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },


  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({ url: path })
    }
  },
  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },
  makeCallPhone: function (e) {
    app.saveFormId(e.detail.formId);
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function (e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function (e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },
  //点击图片放大
  showEWM: function (e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log("showEWM", shareImgUrl)
    if (!shareImgUrl){
      return
    }
    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },

  //页面分享
  onShareAppMessage: function () {
    var that = this;

    var inviteuid = that.data.inviteuid ? that.data.inviteuid : that.data.uid;
    console.log("分享id2" + inviteuid);
    var textcontent = that.data.tc == 1 ? '，這是我的新名片，敬請惠存' : '，这是我的新名片，敬请惠存';

    var titleText = '我是' + that.data.userinfo.uname + textcontent;
    var option=''
    if(that.data.room){
      var room = that.data.room;
      textcontent = that.data.tc == 1 ? '我是' + room.building + room.number + '，歡迎入住' : '我是' + room.building + room.number+'，欢迎入住';
      titleText = textcontent;
      console.log("option",that.data.option)
      var roomstr = JSON.stringify(that.data.room)
      option = "&roomstr=" + roomstr;

    }
    return {
      title: titleText,
      path: '/pages/talent-mycard/talent-mycard?&inviteuid=' + inviteuid + option
    };
  }, 


  // 读取动态 （近况）
  loadGHS: function (cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghs",
      orgid: util.orgid,
      page: cpage,
      num: 10
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("供货商数据：", result);
        if (!result.msg) {
          // result.forEach(function (m, i) {
          //   if (m.photos) {
          //     result[i].photosData = m.photos.split(",");
          //   }
          //   result[i].message = app.parseHTMLText(m.message);
          // });

          // if (cpage <= 1) {
          //   that.setData({
          //     ghsData: result
          //   });

          // } else {
            that.setData({
              ghsData: that.data.ghsData.concat(result)
            });
            console.log(that.data.userinfo.stores);
            if(that.data.userinfo.stores !=undefined){
              for(var i=0;i<result.length;i++){
                if(result[i].uid == that.data.userinfo.stores){
                  that.setData({
                    ghsData: that.data.ghsData.concat(result[i])
                  });
                }
              }
              console.log(that.data.ghsData);
            }else{
              // that.setData({
              //       ghsData: that.data.ghsData.concat(result)
              //     });
              console.log(that.data.ghsData);
            }
            
            console.log(that.data.ghsData);

          // }
        } else {
          if (cpage <= 1) {

            that.setData({
              ghsData: []
            });

          }

          hasMore = false;


        }
        // loadingMore = false;

        if (that.data.ghsData.length <= 0) {
          that.setData({
            hasData: false
          })
        } else {
          that.setData({
            hasData: true
          })
        }
        wx.hideLoading();
      }
    });
  },

  goMapView: function (e) {
    var addr = e.currentTarget.dataset.addr;
    var lat = parseFloat(addr.lat);
    var lon = parseFloat(addr.lon);
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 20,
      name: addr.name,
      address: addr.address
    })
  },

  touchStart: function (e) {
    console.log("touchS" + e);
    //判断是否只有一个触摸点
    if (e.touches.length == 1) {
      //记录触摸起始位置的X坐标
      startX = e.touches[0].clientX
    }
  },

  touchMove: function (e) {
    console.log("touchM:" + e);
    var that = this
    //获取手指触摸的是哪一个item
    var index = e.currentTarget.dataset.idx;

    var list = that.data.btnList;
    if (e.touches.length == 1) {
      //记录触摸点位置的X坐标
      var moveX = e.touches[0].clientX;
      //计算手指起始点的X坐标与当前触摸点的X坐标的差值
      var disX = moveX - startX;
      //hiddenWidth 为右侧按钮区域的宽度
      var hiddenWidth = that.data.hiddenWidth;
      var txtStyle = 0;
      if (disX == 0 || disX > 0) {

        txtStyle = list[index].right > -hiddenWidth && list[index].right - disX > -hiddenWidth ? list[index].right - disX : -hiddenWidth;
        
      } else if (disX < 0) {
        txtStyle = -hiddenWidth-disX;
        if (-disX >= hiddenWidth) {
         
          txtStyle = 0;
        }
      }
      
      //将拼接好的样式设置到当前item中
      list[index].right = txtStyle;
      //更新列表的状态
      this.setData({
        btnList: list
      });
    }
  },

  touchEnd: function (e) {
    console.log("touchEnd:" + e);
  },

  getCircleUserinfo: function (uid) {
    var that = this;
    app.GetUserInfo(uid, function (res) {
      console.log("getCircleUserinfo:",res);
      that.setData({
        userinfo:res,
      })
      var tc = app.get_tc();//简体繁体转换
      var titlename = tc == 1 ? '個人名片' : '个人名片';
      if (util.orgid == 15671) {
        titlename = tc == 1 ? '個人簡歷' : '个人简历';
      }
      wx.setNavigationBarTitle({
        title: that.data.userinfo.uname + titlename,
      }); 
    });
  },

  videoErrorCallback: function (e) {
    console.log('视频错误信息:'+e.detail.errMsg);
  },

  changeTabCata: function (e) {
    console.log("Tabcurrcata", e.currentTarget.dataset.current)
    var cur = e.currentTarget.dataset.current;
    if (this.data.tabcurrcata == cur) { return false; }
    else {
      this.setData({
        tabcurrcata: cur
      })
    }
  },

})